<template>
  <a-modal
    title='新建数据'
    :width='640'
    :visible='visible'
    :confirmLoading='loading'
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning='loading'>
      <a-form :form='form' v-bind='formLayout'>
        <a-form-item label='系统'>
          <a-select
            :options='systemList'
            @change='handleChangeSystem'
            v-decorator="[
              'systemDicId',
              { rules: [{ required: true, message: '请选择系统!'}] },
            ]"
          >
          </a-select>
        </a-form-item>
        <a-form-item label='设备'>
          <a-select
            :options='deviceList'
            @change='handleChangeDevice'
            v-decorator="[
              'deviceDicId',
              { rules: [{ required: true, message: '请选择设备!' }] },
            ]">
          </a-select>
        </a-form-item>
        <a-form-item label='点位'>
          <a-row>
            <a-col :span='20'>
              <a-select
                mode='multiple'
                :options='pointList'
                v-decorator="[
              'pointDicList',
              { rules: [{ required: true, message: '请选择点位!' }] },
            ]">
              </a-select>
            </a-col>
            <a-col :span='3' :offset='1'>
              <a-switch
                :disabled='!pointList.length'
                checkedChildren='全选'
                unCheckedChildren='取消全选'
                @change='changePointSelectState'
                v-model='selectFlag' />
            </a-col>
          </a-row>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { mapState } from 'vuex'
import { findSelectableDataPoint } from '@/api/realTimeDataConfig'

const fields = ['systemDicId', 'deviceDicId', 'pointDicList']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    moduleId: {
      type: String,
      default: ''
    }
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      }
    }
    return {
      form: this.$form.createForm(this),
      systemList: [],
      deviceList: [],
      pointList: [],
      systemId: '',
      deviceId: '',
      selectFlag: true
    }
  },
  created() {
    fields.forEach(v => this.form.getFieldDecorator(v))
    // 防止表单未注册
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      fields.forEach(v => this.form.getFieldDecorator(v))
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
    this.getSystemList()
  },
  computed: {
    ...mapState({
      moduleList: state => state.dataDicInfo.modules.map(item => {
        return {
          key: item.code,
          label: item.name,
          id: item.id
        }
      })
    })
  },
  methods: {
    changePointSelectState(val) {
      if (val) {
        this.form.setFieldsValue({
          pointDicList: this.pointList.map(item => item.key)
        })
        return
      }
      this.form.setFieldsValue({
        pointDicList: []
      })
    },
    handleChangeDevice(val) {
      this.deviceId = val
      this.getPointList()
      this.form.setFieldsValue({
        pointDicList: []
      })
    },
    handleChangeSystem(val) {
      this.systemId = val
      this.form.setFieldsValue({
        deviceDicId: '',
        pointDicList: []
      })
      this.getDeviceList()
    },

    async getSystemList() {
      if (!this.moduleId) {
        return
      }
      const currentModuleItem = this.moduleList.find(item => item.key === this.moduleId)
      let result = null
      this.$emit('up-loading', true)
      try {
        result = await findSelectableDataPoint({
          moduleDicId: currentModuleItem.id
        })
        this.systemList = result.map(item => {
          return {
            key: item.id,
            label: item.name,
            code: item.code
          }
        })
      } finally {
        this.$emit('up-loading', false)
      }
    },

    // 获取设备列表
    async getDeviceList() {
      const systemDicId = this.systemId
      if (!systemDicId) {
        return
      }
      this.$emit('up-loading', true)
      let result = null
      try {
        result = await findSelectableDataPoint({
          systemDicId: systemDicId
        })
        this.deviceList = result.map(item => {
          return {
            key: item.id,
            label: item.name,
            code: item.code
          }
        })
      } finally {
        this.$emit('up-loading', false)
      }
    },

    // 获取点位列表
    async getPointList() {
      const deviceDicId = this.deviceId
      if (!deviceDicId) {
        return
      }
      this.$emit('up-loading', true)
      let result = null
      try {
        result = await findSelectableDataPoint({
          deviceDicId
        })
        this.pointList = result.map(item => {
          return {
            key: item.id,
            label: item.name,
            code: item.code
          }
        })
        this.form.setFieldsValue({
          pointDicList: this.pointList.map(item => item.key)
        })
      } finally {
        this.$emit('up-loading', false)
      }
    }
  }
}
</script>
